<?php
require_once ('../../libraryfiles/config.php');

$action = isset ( $_GET ['action'] ) ? $_GET ['action'] : '';

switch ($action) {

	case 'add' :
		addCategory ();
		break;

	case 'modify' :
		modifyCategory ();
		break;
	case 'delete' :
		deleteCategory ();
		break;
	case 'updateState' :
		updateState ();
		break;
	case 'publish' :
		publishSelected ();
		break;
	case 'muliDelete' :
		muliDelete ();
		break;
	case 'deleteImage' :
		deleteImage ();
		break;
	case 'publish' :
		publishSelect ();
		break;

	default :
		// if action is not defined or unknown
		// move to main user page
		header ( 'Location: index.php' );
}

function addCategory() {
	
	$image = new ResizeClassImage();
	$Name = ampReplace ( $_POST ['txtName'] );
	$Name = htmlspecialchars ( $Name );
	// $desc = addslashes($_POST['texteditor']);
	$cate = isset ( $_POST ['cate'] ) ? $_POST ['cate'] : 0;
	$ID = $_POST ['hidid'];
	// $cat_image = ampReplace($_POST['txtimage']);
	$cat_class = ampReplace ( $_POST ['txtClass'] );

	/* upload image */
	$cat_image = '';

	$detectExist_q = '';
	if (! empty ( $ID )) {
		$modify = true;
		$link = "&id=" . $ID;
		$detectExist_q .= " AND id != " . $ID;
	}
	if ('' == $_FILES ['txtimage']['name']) {
		if (!$modify) {
			header ( 'Location:'.base_url_admin.'/category/index.php?view=add&error=empty_file');
			exit();
		}
	} else {
		
		if ($_FILES ["txtimage"] ["type"] == "image/png") {
			
			$image->load( $_FILES ["txtimage"] ["tmp_name"]);
			
			$fileName = $_FILES ["txtimage"] ["name"];
			// check folder image before upload
			if (file_exists('image/' . $fileName)) {
				$fileName = $image->random ( 5 ) . '-' . $fileName;
			}
			// resize image
			if ($image->getHeight() < 20) {
				header ( 'Location:'.base_url_admin.'/category/index.php?view=add&error=file_size');
				exit();
			} else {
				 $path_f = FRONT_SITE_DIR.DS.'admin'.DS.'category'.DS.'image'.DS;
				move_uploaded_file($_FILES["txtimage"]["tmp_name"],$path_f . $fileName);
				
			}
			$cat_image = $fileName;
		} else {
			header ('Location:'.base_url_admin.'/category/index.php?view=add&error=invalid_file');
			exit();
		}
	}
	
	/* end upload image */
	
	 if (isset($modify)) {
		/* remove old image */
		$getimg = mysql_query ( "SELECT * FROM " . Tblcategory::TableName . " WHERE " . Tblcategory::id . " =" . $ID );
		if (mysql_num_rows ( $getimg ) > 0) {
			while ( $arr = mysql_fetch_array ( $getimg ) ) {
				$Oldimg = $arr [Tblcategory::cat_image];
			}
		}
		if ('' != $_FILES ['txtimage']['name']) {
			if (file_exists ( "image/" . $Oldimg )) {
				unlink ( "image/" . $Oldimg );
			}
		} else {
			$cat_image = $Oldimg;
		}
		/* end remove old image */

		 $sql_u = "UPDATE tblcategory SET category_name = '".$Name."', parent_id = '".$cate."', cat_image ='".$cat_image."',cat_class='".$cat_class."', mdate=NOW() WHERE id = '".$ID."'";
		mysql_query ( $sql_u );
	} else {
		
		 $sql = "INSERT INTO tblcategory(category_name, category_desc, parent_id, cdate, mdate, status,cat_image,cat_class) VALUES ('".@$Name."', '".@$desc."','".@$cate."', NOW(), NOW(),1,'".@$cat_image."','".@$cat_class."')";
		mysql_query ( $sql );
	}
	header ( 'Location:'.base_url_admin.'/category/index.php');
	exit();
}

/*
 * Modify a user
 */
function updateState() {
	$cateId = $_POST ['chkall'];
	foreach ( $cateId as $value ) {
		$sql = "UPDATE tblcategory
	          SET state = '0' , last_modify= NOW()
			  WHERE id = $value";

		mysql_query ( $sql );
	}
	header ( 'Location: ' . $_SESSION ['shop_return_url'] );
}
function publishSelected() {
	if (isset ( $_POST ['id'] )) {
		if (isset ( $_GET ['publish'] ) && ( int ) $_GET ['publish'] >= 0 && ( int ) $_GET ['publish'] <= 1) {
			$state = ( int ) $_GET ['publish'];
		} else {
			header ( 'Location:'.base_url_admin.'/category/index.php' );
			exit ();
		}

		// Statement to get selected id
		$id = (is_array ( $_POST ['id'] )) ? implode ( ',', $_POST ['id'] ) : $_POST ['id'];

		// Statement to publish/unpublish selected id
		publish ( 'tblcategory', $state, $id );

		$sql_pub = "UPDATE tblcategory SET status = $state WHERE parent_id IN ($id)";
		mysql_query ( $sql_pub );
	}

	header ( 'Location:'.base_url_admin.'/category/index.php?' . getAllGetParams ( array (
			'view',
			'action',
			'publish'
	) ) );
	exit ();
}
function muliDelete() {
	if (isset ( $_POST ['id'] )) {
		// Statement to get selected id
		$ids = (is_array ( $_POST ['id'] )) ? implode ( ',', $_POST ['id'] ) : $_POST ['id'];

		// select to get old image and remove it
		$sqlSelect = 'SELECT cat_image FROM tblcategory WHERE id IN (' . $ids . ')';
		$result = mysql_query($sqlSelect);
		while ($oldImagesObject = mysql_fetch_object($result)) {
			$oldImage = $oldImagesObject->cat_image;
			removeImage($oldImage);
		}

		// select to get old image of it child to remove it
		$sqlSelectParent = 'SELECT cat_image FROM tblcategory WHERE parent_id IN (' . $ids . ')';
		$resultParent = mysql_query($sqlSelectParent);
		while ($oldImagesObject = mysql_fetch_object($resultParent)) {
			$oldImage = $oldImagesObject->cat_image;
			removeImage($oldImage);
		}

		// Statment to delete selected id
		$sql = "DELETE FROM tblcategory WHERE id IN ($ids)";
		mysql_query ( $sql );
		$sql1 = "DELETE FROM tblcategory WHERE parent_id IN ($ids)";
		mysql_query ( $sql1 );
	}
	header ( 'Location: ' . $_SESSION ['shop_return_url'] );
}

function removeImage ($fileName) {
	if (file_exists('image/' . $fileName)) {
		unlink('image/' . $fileName);
	}
}
/*
 * Remove Category
 */
function deleteCategory() {
	if (isset ( $_GET ['cateId'] ) && ( int ) $_GET ['cateId'] > 0) {
		$cateId = ( int ) $_GET ['cateId'];
	} else {
		header ( 'Location: index.php' );
	}
	$sql = "DELETE FROM tblcategory WHERE id = $cateId OR category_parent = $cateId";
	mysql_query ( $sql );

	header ( 'Location: ' . $_SESSION ['shop_return_url'] );
}

/*
 * Upload an image and return the uploaded image name
 */
function uploadProductImage($inputName, $uploadDir) {
	$image = $_FILES [$inputName];
	$imagePath = '';
	$thumbnailPath = '';

	// if a file is given
	if (trim ( $image ['tmp_name'] ) != '') {
		$ext = substr ( strrchr ( $image ['name'], "." ), 1 ); // $extensions[$image['type']];
		// generate a random new file name to avoid name conflict
		$imagePath = md5 ( rand () * time () ) . ".$ext";

		list ( $width, $height, $type, $attr ) = getimagesize ( $image ['tmp_name'] );
		if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
			$result = createThumbnail ( $image ['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH );
			$imagePath = $result;
		} else {
			echo 11;die;
			$result = move_uploaded_file ( $image ['tmp_name'], $uploadDir . $imagePath );
		}

		if ($result) {
			// create thumbnail
			$thumbnailPath = md5 ( rand () * time () ) . ".$ext";
			$result = createThumbnail ( $uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH );

			// create thumbnail failed, delete the image
			if (! $result) {
				unlink ( $uploadDir . $imagePath );
				$imagePath = $thumbnailPath = '';
			} else {
				$thumbnailPath = $result;
			}
		} else {
			// the product cannot be upload / resized
			$imagePath = $thumbnailPath = '';
		}
	}

	return array (
			'image' => $imagePath,
			'thumbnail' => $thumbnailPath
	);
}
function deleteImage() {
	if (isset ( $_GET ['cateId'] ) && ( int ) $_GET ['cateId'] > 0) {
		$cateId = ( int ) $_GET ['cateId'];
	} else {
		header ( 'Location:'.base_url_admin.'/category/index.php' );
	}

	$deleted = _deleteImage ( $cateId );

	// update the image and thumbnail name in the database
	$sql = "UPDATE tblcategory
			SET image = '', thumbnail = ''
			WHERE id = $cateId";
	mysql_query ( $sql );

	header ( "Location:".base_url_admin."/category/index.php?view=modify&cateId=$cateId" );
}
function _deleteImage($cateId) {
	// we will return the status
	// whether the image deleted successfully
	$deleted = false;

	$sql = "SELECT image, thumbnail
	        FROM tblcategory
			WHERE id = $cateId";
	$result = mysql_query ( $sql ) or die ( 'Cannot delete product image. ' . mysql_error () );

	if (dbNumRows ( $result )) {
		$row = mysql_fetch_assoc ( $result );
		extract ( $row );

		if ($image && $thumbnail) {
			// remove the image file
			$deleted = @unlink ( DOC_ROOT . "images/category/$image" );
			$deleted = @unlink ( DOC_ROOT . "images/category/$thumbnail" );
		}
	}

	return $deleted;
}
function publishSelect() {
	if (isset ( $_POST ['id'] )) {
		if (isset ( $_GET ['publish'] ) && ( int ) $_GET ['publish'] >= 0 && ( int ) $_GET ['publish'] <= 1) {
			$state = ( int ) $_GET ['publish'];
		} else {
			header ( 'Location:'.base_url_admin.'/category/index.php' );
			exit ();
		}
		// Statement to get selected id
		$id = (is_array ( $_POST ['id'] )) ? implode ( ',', $_POST ['id'] ) : $_POST ['id'];

		// Statment to delete selected id
		$sql = "UPDATE tblcategory SET status = $state WHERE id IN ($id)";
		mysql_query ( $sql );
	}
	header ( 'Location:'.base_url_admin.'/category/index.php' );
}

?>